package cn.study.concurrenttools.countdownlatchp;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @Author     ：跟大佳一起学架构
 * @Description：CountDownLatchDemo  比赛例子
 */
public class CountDownLatchDemo {
    private static CountDownLatch pre = new CountDownLatch(5);
    private static CountDownLatch begin = new CountDownLatch(1);
    private static CountDownLatch end = new CountDownLatch(5);
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0;i<5;i++){
            new Thread(()->{
                try {
                    Thread.sleep(new Random().nextInt(2001)+1000);
                    System.out.println("参赛者"+Thread.currentThread().getName()+"已经准备好");
                    pre.countDown(); //准备完毕，计数器减一
                    begin.await(); //等待裁判吹哨
                    System.out.println("参赛者"+Thread.currentThread().getName()+"开始奔跑");
                    Thread.sleep(new Random().nextInt(4001)+1000);
                    System.out.println("参赛者"+Thread.currentThread().getName()+"到达终点");
                    end.countDown();// 参赛者到达终点，计数器减一
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
        pre.await(); //等待所有参赛者准备
        System.out.println("所有参赛者准备完毕");
        begin.countDown(); //所有参赛者准备完毕就开始吹哨
        end.await(); //等待所有参赛者到达终点
        System.out.println("比赛结束");
    }
}